{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "import json\n",
    "from datetime import datetime\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Assets():\n",
    "    def __init__(self, isin):\n",
    "        self.isin = isin\n",
    "\n",
    "    def _xetra_history(self, start_date, end_date, periode='day'):\n",
    "        df = pd.DataFrame(pd.bdate_range(start_date, end_date, freq='B'), columns=['date'])\n",
    "        df.set_index('date', inplace=True)\n",
    "\n",
    "        limit = (datetime.strptime(end_date, '%Y-%m-%d').year - datetime.strptime(start_date, '%Y-%m-%d').year+1) * 253\n",
    "\n",
    "        api_url = 'https://api.boerse-frankfurt.de/data/price_history?limit=' + str(limit) + '&offset=0&isin=' + str(self.isin) + '&mic=XETR&minDate=' + str(start_date) + '&maxDate=' + str(end_date)\n",
    "        req = requests.get(api_url)\n",
    "        json_data = req.json()['data']\n",
    "            \n",
    "        df_prices = pd.DataFrame(json_data)\n",
    "        df_prices.set_index('date', inplace=True)\n",
    "        df_prices.sort_index(inplace=True)\n",
    "            \n",
    "        df = pd.merge(df, df_prices, how='left', left_index=True, right_index=True)\n",
    "        df.dropna(how='all', inplace=True)          \n",
    "        return df\n",
    "    \n",
    "    \n",
    "    def _langschwarz_history(self, start_date, end_date, periode):\n",
    "        pass\n",
    "        \n",
    "        \n",
    "    def historical_prices(self, start_date, end_date, periode='day', data_source='xetra'):\n",
    "        if data_source == 'xetra':\n",
    "            return self._xetra_history(start_date, end_date)\n",
    "        \n",
    "        if data_source == 'langschwarz':\n",
    "            return self._langschwarz_history(start_date, end_date)\n",
    "       \n",
    "    \n",
    "    def historical_ticker(self, start_datetime, end_datetime):\n",
    "        #start_datetime example: '2020-01-01 16:45'\n",
    "        start_date, end_date = start_datetime.split(' ')[0], end_datetime.split(' ')[0]\n",
    "        start_h, start_min = start_datetime.split(' ')[-1].split(':')[0], start_datetime.split(' ')[-1].split(':')[-1]\n",
    "        end_h, end_min = end_datetime.split(' ')[-1].split(':')[0], end_datetime.split(' ')[-1].split(':')[-1]\n",
    "        api_url = 'https://api.boerse-frankfurt.de/data/tick_data?limit=2500&offset=0&isin='+str(self.isin)+'&mic=XETR&minDateTime='+str(start_date)+'T'+str(start_h)+'%3A'+str(start_min)+'%3A00.000Z&maxDateTime='+str(end_date)+'T'+str(end_h)+'%3A'+str(end_min)+'%3A00.000Z'\n",
    "        req = requests.get(api_url)\n",
    "        json_data = req.json()['ticks']\n",
    "        df_ticker = pd.DataFrame(json_data)\n",
    "        df_ticker.set_index('time', inplace=True)\n",
    "        return df_ticker\n",
    "    \n",
    "    \n",
    "    def get_price(self):\n",
    "        api_url = 'https://api.boerse-frankfurt.de/data/price_information?isin=' + str(self.isin) + '&mic=XETR'\n",
    "        req = requests.get(api_url, stream=True)        \n",
    "        for line in req.iter_lines():\n",
    "            if line:\n",
    "                price = float(json.loads(line[5:].decode('utf-8')).get('lastPrice'))\n",
    "                break\n",
    "        return price\n",
    "    \n",
    "    \n",
    "    def get_bid_ask(self):\n",
    "        api_url = 'https://api.boerse-frankfurt.de/data/bid_ask_overview?isin=' + str(self.isin) + '&mic=XETR'\n",
    "        req = requests.get(api_url, stream=True)\n",
    "        for line in req.iter_lines(decode_unicode=True):\n",
    "            if line:\n",
    "                json_data = json.loads(line[5:]).get('data')[0]\n",
    "                bid_price, ask_price = float(json_data.get('bidPrice')), float(json_data.get('askPrice'))\n",
    "                break\n",
    "        return bid_price, ask_price\n",
    "              \n",
    "        \n",
    "    def get_fee(self):\n",
    "        api_url = 'https://api.boerse-frankfurt.de/data/fees_etp?isin=' + str(self.isin)\n",
    "        req = requests.get(api_url, stream=True)        \n",
    "        for line in req.iter_lines():\n",
    "            if line:\n",
    "                total_expense_perc = float(json.loads(line.decode('utf-8')).get('totalExpensePercent'))\n",
    "                break\n",
    "        return total_expense_perc                  \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "41.235\n",
      "41.279\n"
     ]
    }
   ],
   "source": [
    "bid_price, ask_price = Assets('IE00B42Z5J44').get_bid_ask()\n",
    "print(bid_price)\n",
    "print(ask_price)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>price</th>\n",
       "      <th>turnover</th>\n",
       "      <th>turnoverInEuro</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>time</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2020-03-23T17:36:06+01:00</th>\n",
       "      <td>38.391</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T15:36:13+01:00</th>\n",
       "      <td>38.635</td>\n",
       "      <td>28.0</td>\n",
       "      <td>1081.780</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T14:45:00+01:00</th>\n",
       "      <td>38.322</td>\n",
       "      <td>185.0</td>\n",
       "      <td>7089.570</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T14:44:04+01:00</th>\n",
       "      <td>38.444</td>\n",
       "      <td>82.0</td>\n",
       "      <td>3152.408</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T14:39:34+01:00</th>\n",
       "      <td>38.483</td>\n",
       "      <td>103.0</td>\n",
       "      <td>3963.749</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T13:19:10+01:00</th>\n",
       "      <td>39.115</td>\n",
       "      <td>104.0</td>\n",
       "      <td>4067.960</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T13:18:09+01:00</th>\n",
       "      <td>39.227</td>\n",
       "      <td>20.0</td>\n",
       "      <td>784.540</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T13:12:15+01:00</th>\n",
       "      <td>39.004</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T13:04:14+01:00</th>\n",
       "      <td>38.362</td>\n",
       "      <td>104.0</td>\n",
       "      <td>3989.648</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T12:52:41+01:00</th>\n",
       "      <td>38.103</td>\n",
       "      <td>290.0</td>\n",
       "      <td>11049.870</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T12:52:40+01:00</th>\n",
       "      <td>38.103</td>\n",
       "      <td>9.0</td>\n",
       "      <td>342.927</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T12:47:36+01:00</th>\n",
       "      <td>38.158</td>\n",
       "      <td>75.0</td>\n",
       "      <td>2861.850</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T12:45:03+01:00</th>\n",
       "      <td>38.212</td>\n",
       "      <td>104.0</td>\n",
       "      <td>3974.048</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T10:58:20+01:00</th>\n",
       "      <td>38.566</td>\n",
       "      <td>2992.0</td>\n",
       "      <td>115389.472</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2020-03-23T10:55:17+01:00</th>\n",
       "      <td>38.566</td>\n",
       "      <td>900.0</td>\n",
       "      <td>34709.400</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                            price  turnover  turnoverInEuro\n",
       "time                                                       \n",
       "2020-03-23T17:36:06+01:00  38.391       0.0           0.000\n",
       "2020-03-23T15:36:13+01:00  38.635      28.0        1081.780\n",
       "2020-03-23T14:45:00+01:00  38.322     185.0        7089.570\n",
       "2020-03-23T14:44:04+01:00  38.444      82.0        3152.408\n",
       "2020-03-23T14:39:34+01:00  38.483     103.0        3963.749\n",
       "2020-03-23T13:19:10+01:00  39.115     104.0        4067.960\n",
       "2020-03-23T13:18:09+01:00  39.227      20.0         784.540\n",
       "2020-03-23T13:12:15+01:00  39.004       0.0           0.000\n",
       "2020-03-23T13:04:14+01:00  38.362     104.0        3989.648\n",
       "2020-03-23T12:52:41+01:00  38.103     290.0       11049.870\n",
       "2020-03-23T12:52:40+01:00  38.103       9.0         342.927\n",
       "2020-03-23T12:47:36+01:00  38.158      75.0        2861.850\n",
       "2020-03-23T12:45:03+01:00  38.212     104.0        3974.048\n",
       "2020-03-23T10:58:20+01:00  38.566    2992.0      115389.472\n",
       "2020-03-23T10:55:17+01:00  38.566     900.0       34709.400"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hist_ticker = Assets('IE00B42Z5J44').historical_ticker(start_datetime='2020-03-23 09:34', end_datetime='2020-03-23 17:00')\n",
    "hist_ticker"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
